//
//  KeychainItem.m
//  MailDelivery
//
//  Created by Dante Palacios on 9/24/09.
//  Copyright 2009 Dante Palacios. All rights reserved.
//

#import "KeychainItem.h"

#import "Funtions.h"
#import "Macros.h"


@implementation KeychainItem

@synthesize keychainItemRef = _keychainItemRef;
@synthesize hostName = _hostName;
@synthesize userName = _userName;
@synthesize password = _password;

- (void)dealloc
{
	if (_keychainItemRef)
	{
		CFRelease(_keychainItemRef);
	}
	
	[_hostName release];
	_hostName = nil;
	[_userName release];
	_userName = nil;
	[_password release];
	_password = nil;

	[super dealloc];
}

- (NSString *)userName
{
    return AtomicAutoreleasedGet(_userName);
}

- (void)setUserName:(NSString *)value
{
	@synchronized(self)
	{
		if (_userName && (_userName != value) && !IsMobileMeHost([self hostName]))
		{
			if (ModifyKeychainItemRef(_keychainItemRef, kSecAccountItemAttr, value) == noErr)
			{
				//NSLog(@"%@ userName changed to \"%@\"", self, value);
			}
		}
		
		if (_userName != value)
		{
			[_userName release];
			_userName = [value copy];
		}
	}
}

- (NSString *)password 
{
    return AtomicAutoreleasedGet(_password);
}

- (void)setPassword:(NSString *)value 
{
	@synchronized(self)
	{
		if (_password && (_password != value) && !IsMobileMeHost([self hostName]))
		{
			OSStatus status = SecKeychainItemModifyAttributesAndData(_keychainItemRef, NULL, (UInt32) strlen([value UTF8String]), (void *) [value UTF8String]);
			
			if (status != noErr)
			{
				CFStringRef errMess = SecCopyErrorMessageString(status, NULL);
				NSLog(@"%@ Error:%@", self, (NSString *)errMess);
				CFRelease(errMess);
			}
		}
		
		if (_password != value)
		{
			[_password release];
			_password = [value copy];
		}
	}
}

- (NSString *)hostName 
{
    return AtomicAutoreleasedGet(_hostName);
}

- (void)setHostName:(NSString *)value 
{
	@synchronized(self) 
	{
		if (_hostName && (_hostName != value) && !IsMobileMeHost(value)) 
		{
			if (ModifyKeychainItemRef(_keychainItemRef, kSecServerItemAttr, value) == noErr) 
			{
				//NSLog(@"%@ hostName changed to \"%@\"", self, value);
			}
		}
		
		if (_hostName != value) 
		{
			[_hostName release];
			_hostName = [value copy];
		}
	}
}

@end

OSStatus ModifyKeychainItemRef(SecKeychainItemRef itemRef, SecItemAttr itemAttribute, NSString *value)
{
	const char *newValue = [value UTF8String];
	SecKeychainAttribute attributes[1];
	attributes[0].tag = itemAttribute;
	attributes[0].length = (UInt32)strlen(newValue);
	attributes[0].data = (void *)newValue;
	
	SecKeychainAttributeList list;
	list.count = 1;
	list.attr = attributes;
	
	OSStatus status = SecKeychainItemModifyAttributesAndData(itemRef, &list, 0, NULL);
	
	if (status != noErr)
	{
		CFStringRef errMess = SecCopyErrorMessageString(status, NULL);
		NSLog(@"%@ Error:%@", [KeychainItem class], (NSString *)errMess);
		CFRelease(errMess);
		return status;
	}
	
	return status;
}
